//
//  NSObject+Extension.m
//  DEMO
//
//  Created by J on 16/5/28.
//  Copyright © 2016年 J. All rights reserved.
//

#import "NSObject+Extension.h"
#import <objc/runtime.h>
//
//  NSArray+Swizzle.m
//  DEMO
//
//  Created by J on 16/5/27.
//  Copyright © 2016年 J. All rights reserved.
//

@implementation NSObject (Swizzle)
+ (void)load{
    
    
    Class arrayClass = objc_getClass("__NSArrayM");
    Method originalMethod = class_getClassMethod(arrayClass, @selector(objectAtIndex:));
    Method categoryMethod = class_getClassMethod(arrayClass, @selector(objectAtIndexAlt:));
    method_exchangeImplementations(originalMethod, categoryMethod);
}



void fuck() {
    NSLog(@"fuck");
}


- (id)forwardingTargetForSelector:(SEL)aSelector
{
    if (aSelector == @selector(uppercaseString))
    {
        return@"hello world";
    }
    
    class_addMethod([self class], aSelector, (IMP) dynamicMethodIMP, "v@:");
    return self.class.new;//new一个对象 负责崩溃 返回一个用来执行aSelector的对象
}


void dynamicMethodIMP(id self, SEL _cmd)
{
    printf("SEL %s did not exist\n",sel_getName(_cmd));
}
//
////如果对没有相应方法 如果实现了这个方法 并且添加了selsector 那么执行 否则调用forwardingTargetForSelector  不论这个方法返回什么  如果forwardingTargetForSelector还没找到相应selector那么直接再返回来执行这个方法 如果还是没有就崩溃
//+ (BOOL) resolveInstanceMethod:(SEL)aSEL
//{
//        if (aSEL == @selector(t))
//        {
//    class_addMethod([self class], aSEL, (IMP) dynamicMethodIMP, "v@:");
//    return YES;
//        }
//        return [super resolveInstanceMethod:aSEL];
//}


@end
